package no.ntnu.fp.client;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;

import no.ntnu.fp.model.AbstractModel;
import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.model.Message;
import no.ntnu.fp.model.SuperPackage;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

public class ClientModelHandler {
	
	private static ClientModelHandler mh;
	private ClientConnectionHandler ch;
	
	public ClientModelHandler(ClientConnectionHandler ch) {
		mh = this;
		this.ch = ch;
	}
	
	public void updateModels(String s) {
		
		nu.xom.Builder parser = new nu.xom.Builder(false);
		nu.xom.Document doc = null;
		try {
			doc = parser.build(s, "");
			SuperPackage sp = new SuperPackage(doc);
			sp.run();
		} 
		catch (ValidityException e) {} 
		catch (ParsingException e) {} 
		catch (IOException e) {} 
		catch (SecurityException e) {} 
		catch (IllegalArgumentException e) {} 
		catch (ClassNotFoundException e) {} 
		catch (NoSuchMethodException e) {} 
		catch (IllegalAccessException e) {} 
		catch (InvocationTargetException e) {}
	}
	
	public String constructPacket(List<AbstractModel> models) {
		
		SuperPackage sp = new SuperPackage();
		
		for (AbstractModel a : models) {
			sp.put(a);
		}
		
		return sp.toDocument().toXML().toString();
	}
	
	public String constructPacket(AbstractModel model) {
		
		SuperPackage sp = new SuperPackage();
		
		sp.put(model);
		
		return sp.toDocument().toXML().toString();
	}
	
	public static void updateModel(AbstractModel a) {
		
		String s = mh.constructPacket(a);
		mh.ch.send(s);
	}
}
